package main

import (
	"bufio"
	"errors"
	"os/exec"
	"path/filepath"
	"strings"

	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/storage"
	"fyne.io/fyne/v2/widget"
)

func storeURI(p string) error {
	var err error
	uri := storage.NewFileURI(p)
	loc, err = storage.ListerForURI(uri)
	return err
}

func openZip(fn string) error {
	storeURI(filepath.Dir(fn))
	filename = fn
	password = ""

	cmd := exec.Command("unzip-go", "-l", fn)
	pipeIn, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}
	err = cmd.Start()
	if err != nil {
		pipeIn.Close()
		return err
	}

	bufr := bufio.NewReader(pipeIn)
	data = [][]string{}
	for {
		var line1 string
		line1, err = bufr.ReadString('\n')
		if err != nil {
			break
		}
		//fmt.Println(line1)
		info1 := strings.Split(strings.TrimSpace(line1), "\t")
		if len(info1) != 3 {
			err = errors.New("unzip-go解压失败或版本错误")
			statusInit = "unzip-go解压失败或版本错误"
			break
		}
		data = append(data, info1)
	}
	if len(data) == 0 {
		data = [][]string{[]string{"", "", ""}, []string{"", "", ""}}
		statusInit = fn + " : unzip-go解压失败"
	}
	cmd.Wait()
	return err
}

func unpackZip(fn string) error {
	return unpackZipTo(fn, "")
}

func unpackZipTo(fn string, d string) error {
	var cmd *exec.Cmd
	if len(d) > 0 {
		cmd = exec.Command("unzip-go", "-d", d, fn)
	} else {
		cmd = exec.Command("unzip-go", fn)
	}
	return myRunCmd(cmd, fn)
}

func pickSelected(idx string, fn string) error {
	return pickSelectedTo(idx, fn, "")
}

func pickSelectedTo(idx string, fn string, d string) error {
	var cmd *exec.Cmd
	if len(d) > 0 {
		cmd = exec.Command("unzip-go", "-d", d, "-idx", idx, fn)
	} else {
		cmd = exec.Command("unzip-go", "-idx", idx, fn)
	}
	return myRunCmd(cmd, fn)
}

func myRunCmd(cmd *exec.Cmd, fn string) error {
	pipeIn, err := cmd.StdoutPipe()
	if err != nil {
		status.SetText(err.Error())
		return err
	}
	pipeOut, err := cmd.StdinPipe()
	if err != nil {
		status.SetText(err.Error())
		return err
	}
	err = cmd.Start()
	if err != nil {
		status.SetText(err.Error())
		return err
	}
	status.SetText("正在解压：" + fn)
	bufr := bufio.NewReader(pipeIn)
	line1, err := bufr.ReadString('\n')
	if err == nil {
		if strings.TrimSpace(line1) == "Password:" {
			if len(password) > 0 {
				pipeOut.Write([]byte(password + "\n"))
			} else {
				entry1 := widget.NewPasswordEntry()
				dialog.ShowForm("请输入密码", "确定", "取消", []*widget.FormItem{widget.NewFormItem("密码", entry1)}, func(b bool) {
					if b {
						password = entry1.Text
						pipeOut.Write([]byte(password + "\n"))
					} else {
						cmd.Process.Kill()
					}
				}, myWindow)
			}
		}
	}
	go func() {
		for {
			_, err = bufr.ReadString('\n')
			if err != nil {
				break
			}
		}
		err := cmd.Wait()
		if err != nil {
			status.SetText(err.Error())
		} else {
			status.SetText("解压完成：" + fn)
		}
	}()

	return nil
}
